package hydrap2p.library.listening;

import hydrap2p.library.Database;
import hydrap2p.library.LibraryLogging;
import hydrap2p.library.SharedItemInfo;
import hydrap2p.logging.Level;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.apache.thrift.TException;

public class ListenerSyncerator extends Thread{
	private List<SharedItemInfo> items;
	private Listener client;
	public ListenerSyncerator(List<SharedItemInfo> items, Listener client)
	{
		this.client=client;
		try {
			this.items=Database.getInstance().getAll();
		} catch (SQLException e) {
			LibraryLogging.log(Level.ERROR, "Library - Listener Syncerator", "Could not connect to database");
			this.items=new LinkedList<SharedItemInfo>();		// don't send any information to the clients
		}
	}
	
	@Override
	public void run()
	{
		for (SharedItemInfo item:items)
		{
			try {
				client.execute(new ListenerEvent(ListenerEventType.NewSharedItem,item));
			} catch (TException e) {
				ListenerManager.getInstance().unsubscribe(client.location);
				break;
			}
		}
		client.synced=true;
	}
}
